//
//  SecurityTaskListVC.swift
//  SBSafetyApp
//
//  Created by Aimeow on 2022/11/16.
//  保安管理-任务列表页

import Foundation
import UIKit

class SecurityTaskListVC: SubLevelViewController, PullToRefreshPresentable {
    
    var datas: [LzglbaListModel?] = []
    
    var pageNum = 1
    var totalPage: Int64 = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "任务列表"
        setupUI()
        setupPullToRefresh(on: tableView)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        pageNum = 1
        reloadData()
        reloadStaicData()
    }
    
    deinit {
        tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        reloadData()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        reloadData()
    }
    
    func reloadStaicData() {
        // 保安任务列表统计
        API.getLzglbaWccCount { responseModel in
            DispatchQueue.main.async {
                let m = responseModel.model
                self.segmentedC.updateSegment(withTitle: "今日(\(m?.rrws ?? 0))", at: 0)
                self.segmentedC.updateSegment(withTitle: "本月(\(m?.yrws ?? 0))", at: 1)
                self.segmentedC.updateSegment(withTitle: "本季(\(m?.jrws ?? 0))", at: 2)
                self.segmentedC.updateSegment(withTitle: "今年(\(m?.nrws ?? 0))", at: 3)
            }
        }
    }
    
    func reloadData() {
        // 保安任务列表
        API.getLzglbaTasklist(withParam: SecurityParam(dateType: dateEnum.rawValue, pageNum: pageNum, pageSize: PageSize)) { responseModel in
            DispatchQueue.main.async {
                if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                    self.pageNum -= 1
                    return
                }
                if self.pageNum == 1 {
                    self.datas.removeAll()
                }
                self.totalPage = responseModel.totalPage
                self.datas.append(contentsOf: responseModel.models ?? [])
                self.tableView.tableShowEmpty(withDataCount: self.datas.count)
                self.tableView.reloadData()
            }
        }
    }
    
    @objc func segmentSelected(sender: ScrollableSegmentedControl) {
        let index = sender.selectedSegmentIndex
        dateEnum = CustomDateEnum(rawValue: index + 1) ?? .daily
        pageNum = 1
        reloadData()
    }

    // MARK: - Setup
    func setupUI() {
        self.view.addSubview(segmentedC)
        segmentedC.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.left.right.equalToSuperview()
            make.height.equalTo(45)
        }
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(segmentedC.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
        
        segmentedC.insertSegment(withTitle: "今日(0)", at: 0)
        segmentedC.insertSegment(withTitle: "本月(0)", at: 1)
        segmentedC.insertSegment(withTitle: "本季(0)", at: 2)
        segmentedC.insertSegment(withTitle: "今年(0)", at: 3)
        segmentedC.selectedSegmentIndex = 0
    }
    
    lazy var segmentedC: ScrollableSegmentedControl = {
        let c = ScrollableSegmentedControl()
        c.tintColor = .primary
        c.underlineSelected = true
        c.segmentContentColor = .black
        c.selectedSegmentContentColor = .primary
        c.isFullLine = true
        c.backgroundColor = .white
        let normalAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        let highlightAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        let selectAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        c.setTitleTextAttributes(normalAttrs, for: .normal)
        c.setTitleTextAttributes(highlightAttrs, for: .highlighted)
        c.setTitleTextAttributes(selectAttrs, for: .selected)
        c.addTarget(self, action: #selector(segmentSelected), for: .valueChanged)
        return c
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.register(TaskListCell.self, forCellReuseIdentifier: "SecurityTaskListCell")
        return tableView
    }()
}

extension SecurityTaskListVC: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas[indexPath.row]
        let cell = (tableView.dequeueReusableCell(withIdentifier: "SecurityTaskListCell", for: indexPath)) as! TaskListCell
        cell.buildData(data: data)
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 65
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = datas[indexPath.row]
        if data?.rwzt == "0" {
            navigationController?.pushViewController(SecurityTaskEditVC(withModal: data!), animated: true)
        } else {
            navigationController?.pushViewController(SecurityTaskDetailVC(withId: data?.id), animated: true)
        }
    }
}
